package org.markwebb.mina.playground.hbfilter.client;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ConnectFuture;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.transport.socket.nio.SocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HbClient extends IoHandlerAdapter {
	
	 private static final Logger log = LoggerFactory.getLogger( HbClient.class );
	
	public HbClient(String host, int port) {

		SocketConnector connector = new SocketConnector();
		
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
        chain.addLast( "logger", new LoggingFilter() );
		
		connector.setHandler( this );
		InetSocketAddress addr = new InetSocketAddress(host, port);
		ConnectFuture connectFuture = connector.connect(addr);
		
		//connectFuture.join(100);
		
		if (connectFuture.isConnected()) {
			log.debug("....connected");
		}
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		
		ByteBuffer buf = ( ByteBuffer ) message;
		System.out.println("Message received - " + 
				new String( buf.getString(Charset.defaultCharset().newDecoder())));
	}

	public static void main(String[] args) {

		String host = args[0];
		int port = Integer.parseInt(args[1]);

		new HbClient(host, port);
	}
}
